#!/usr/bin/python3
# -*- coding: UTF-8 -*-

import pymysql
from DBUtils.PooledDB import PooledDB
from db import config as config

class Mysql(object):
    __pool = None
    def __enter__(self):
        self.conn = self.__getConn()
        self.cursor = self.conn.cursor()
        return self;

    @staticmethod
    def __getConn():
        if Mysql.__pool is None:
            __pool = PooledDB(creator=pymysql, mincached=config.DB_MIN_CACHED , maxcached=config.DB_MAX_CACHED ,
            				  maxshared=config.DB_MAX_SHARED, maxconnections=config.DB_MAX_CONNECYIONS,
                              host=config.DB_HOST , port=config.DB_PORT , user=config.DB_USER , passwd=config.DB_PWD ,
                              db=config.DB_NAME,use_unicode=False,charset=config.DB_CHARSET)
        return __pool.connection()

    def __exit__(self, type, value, trace):
        self.cursor.close()
        self.conn.close()

def getConnection():
    return Mysql()